﻿<%@ WebHandler Language="C#" Class="MfgProblemDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/*
 * Description: 生产问题处理看板
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * Date:2022.8.29
 */

public class MfgProblemDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "exportData":
                        exportData(jObject);
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    string getDataSql(JObject jObject)
    {
        string sql = @"
SELECT t.*,CASE WHEN SYSDATE <= t.linjinqidate THEN 'normal'
                WHEN SYSDATE > t.linjinqidate AND SYSDATE <= t.needcompletedate THEN 'warn'
                WHEN SYSDATE > t.needcompletedate THEN 'danger' END color,
        CASE WHEN ROUND(SYSDATE - t.needcompletedate,2) <= 0 THEN 0 ELSE ROUND(SYSDATE - t.needcompletedate,2) END delayday,
        CASE WHEN SYSDATE - t.needcompletedate <= 0 THEN '0' 
             ELSE extract(day FROM CAST(SYSDATE AS TIMESTAMP) - CAST(t.needcompletedate AS TIMESTAMP)) || '天' ||
                  extract(hour FROM CAST(SYSDATE AS TIMESTAMP) - CAST(t.needcompletedate AS TIMESTAMP)) || '小时' ||
                  extract(minute FROM CAST(SYSDATE AS TIMESTAMP) - CAST(t.needcompletedate AS TIMESTAMP)) || '分'
        END delaytime
FROM (
SELECT up.description,up.ufccreatedate,
       CASE WHEN up.ufcwtdj = 3 THEN up.ufccreatedate + (24*60)/(24*60)
            WHEN up.ufcwtdj = 2 THEN up.ufccreatedate + (8*60)/(24*60)
            WHEN up.ufcwtdj = 1 THEN up.ufccreatedate + (1*60)/(24*60)
            WHEN up.ufcwtdj = 0 THEN up.ufccreatedate + (20)/(24*60) END linjinqidate,
       CASE WHEN up.ufcwtdj = 3 THEN up.ufccreatedate + (24*60*3)/(24*60)
            WHEN up.ufcwtdj = 2 THEN up.ufccreatedate + (24*60)/(24*60)
            WHEN up.ufcwtdj = 1 THEN up.ufccreatedate + (4*60)/(24*60)
            WHEN up.ufcwtdj = 0 THEN up.ufccreatedate + (60)/(24*60) END needcompletedate,
       up.ufccontent,pb.productname,toe.fullname responsibilityEmployeename,rw.workcentername responsibilityWorkcenter,
       cw.workcentername createWorkcenter,ce.fullname createEmployee,up.ufcshenhedate,up.ufcresult,
       DECODE(up.ufcwtdj,'3','一般（3天）',2,'急（1天）',1,'紧急（4H）',0,'特急（1H）') priority,
       CASE WHEN up.ufcstatus=1 THEN '未处理' 
            WHEN up.ufcstatus=2 THEN '处理中' 
            WHEN up.ufcstatus=3 THEN '处理完' 
       END AS ufcstatus,
       up.notes
FROM ufcproblem up
LEFT JOIN ufcproblemtype upt ON upt.ufcproblemtypeid = up.ufcproblemtypeid
LEFT JOIN employee ce ON ce.employeeid = up.ufccreateemployeeid --问题提出人
LEFT JOIN sessionvalues sv ON sv.employeeid = ce.employeeid
LEFT JOIN workcenter cw ON cw.workcenterid = sv.workcenterid --问题提出人所在工区
LEFT JOIN employee toe ON toe.employeeid = up.ufctoemployeeid --责任人
LEFT JOIN workcenter rw ON rw.workcenterid = up.workcenterid --责任工区
LEFT JOIN factory f ON f.factoryid = up.factoryid
LEFT JOIN container c ON c.containerid = up.containerid 
LEFT JOIN product p ON p.productid = c.productid
LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
WHERE up.ufcstatus <> 0 
";
        //责任分厂id
        if (jObject["factoryid"] != null && jObject["factoryid"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryid = '{0}'", jObject["factoryid"].ToString());
        }
        // 责任分厂
        if (jObject["factoryname"] != null && jObject["factoryname"].ToString() != "")
        {
            sql += string.Format(" AND f.factoryname = '{0}'", jObject["factoryname"]);
        }

        //提出工区
        if (jObject["createworcentername"] != null && jObject["createworcentername"].ToString() != "")
        {
            sql += string.Format(" AND cw.workcentername ='{0}'", jObject["createworcentername"]);
        }

        //提出工区id
        if (jObject["createworcenterid"] != null && jObject["createworcenterid"].ToString() != "")
        {
            sql += string.Format(" AND cw.workcenterid ='{0}'", jObject["createworcenterid"]);
        }

        //责任工区id
        if (jObject["resworkcenterid"] != null && jObject["resworkcenterid"].ToString() != "")
        {
            sql += string.Format(" AND rw.workcenterid ='{0}'", jObject["resworkcenterid"]);
        }

        //责任工区
        if (jObject["resworkcentername"] != null && jObject["resworkcentername"].ToString() != "")
        {
            sql += string.Format(" AND rw.workcentername ='{0}'", jObject["resworkcentername"]);
        }

        // 提出工区或责任工区
        if (jObject["workcentername"] != null && jObject["workcentername"].ToString() != "")
        {
            sql += string.Format(" AND (rw.workcentername ='{0}' OR cw.workcentername = '{0}' )", jObject["workcentername"]);
        }

        // 提出工区id或责任工区id
        if (jObject["workcenterid"] != null && jObject["workcenterid"].ToString() != "")
        {
            sql += string.Format(" AND (rw.workcenterid ='{0}' OR cw.workcenterid = '{0}' )", jObject["workcenterid"]);
        }

        if (jObject["status"] != null && jObject["status"].ToString() != "")
        {
            sql += string.Format(" AND up.ufcstatus = '{0}'", jObject["status"]);
        }

        sql += ") t ORDER BY t.ufccreatedate DESC";
        return sql;
    }

    Result getData(JObject jObject)
    {
        string sql = getDataSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    void exportData(JObject jObject)
    {
        string sql = getDataSql(jObject);
        DataTable dtResult = dal.GetDataTable(sql);
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dtResult.Columns.Remove("productname");
        dtResult.Columns.Remove("ufcshenhedate");
        dtResult.Columns.Remove("notes");
        dtResult.Columns.Remove("color");
        dtResult.Columns.Remove("delayday");

        dtResult.Columns["description"].Caption = "问题描述";
        dtResult.Columns["ufccreatedate"].Caption = "提出时间";
        dtResult.Columns["linjinqidate"].Caption = "临超期时间";
        dtResult.Columns["needcompletedate"].Caption = "要求完成时间";
        dtResult.Columns["ufccontent"].Caption = "问题类型";
        dtResult.Columns["responsibilityemployeename"].Caption = "责任人";
        dtResult.Columns["responsibilityworkcenter"].Caption = "责任单位";
        dtResult.Columns["createworkcenter"].Caption = "提出单位";
        dtResult.Columns["createemployee"].Caption = "提出人";
        dtResult.Columns["ufcresult"].Caption = "处理结果";
        dtResult.Columns["priority"].Caption = "需求程度";
        dtResult.Columns["ufcstatus"].Caption = "状态";
        dtResult.Columns["delaytime"].Caption = "超期时间";
        ExportHelper.ExportExcel(dtResult, jObject["title"].ToString());
    }
}